package net.pws.common.poi;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

import org.apache.commons.lang.StringUtils;
import org.apache.poi.xwpf.usermodel.ParagraphAlignment;
import org.apache.poi.xwpf.usermodel.TextAlignment;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFTableCell;

public class ImageOverrider implements CellOverrider {

	private String path;

	private int format = XWPFDocument.PICTURE_TYPE_JPEG;

	private int width = 220;

	private int height = 180;

	public void override(XWPFTableCell cell) {
		if (cell == null || StringUtils.isBlank(path)) {
			return;
		}

		File file = new File(path);
		if (!file.exists()) {
			return;
		}
		FileInputStream is = null;
		try {
			is = new FileInputStream(file);

			cell.removeParagraph(0);
			XWPFParagraph p = cell.addParagraph();
			p.setVerticalAlignment(TextAlignment.CENTER);
			p.setAlignment(ParagraphAlignment.CENTER);
			CustomXWPFDocument document = (CustomXWPFDocument) cell
					.getXWPFDocument();

			String imageId = document.addPictureData(is, format);
			document.insertPicture(p, imageId,
					document.getAllPictures().size() - 1, width, height);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (is != null) {
				try {
					is.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}

	}

	public String getPath() {
		return path;
	}

	public void setPath(String path) {
		this.path = path;
	}

	public int getWidth() {
		return width;
	}

	public void setWidth(int width) {
		this.width = width;
	}

	public int getHeight() {
		return height;
	}

	public void setHeight(int height) {
		this.height = height;
	}

	public int getFormat() {
		return format;
	}

	public void setFormat(int format) {
		this.format = format;
	}

}
